﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Windows.Forms;
using System.Data.Objects;
using ThaiHoa.Win.QLSX.Entity;
using ThaiHoa.Win.QLSX.QuanLyKho.UTI;
using Excel=Microsoft.Office.Interop.Excel;

namespace ThaiHoa.Win.QLSX.QuanLyKho.UI
{
    public partial class frmThepDacDetail : Form
    {
        #region Fields
        QuanLyKhoDBContext db;
        BindingSource thepDacBS;
        BindingSource macVatTuBS;
        private bool HasChanged = false;
        #endregion
        #region Contructor
        public frmThepDacDetail()
        {
            InitializeComponent();
        }
        #endregion
        #region Functions
        private void BindData()
        {
            db = new QuanLyKhoDBContext();                       
            thepDacBS = new BindingSource();
            this.thepDacBS.AddingNew += new AddingNewEventHandler(thepDacBS_AddingNew);
            this.thepDacBS.ListChanged+=new ListChangedEventHandler(thepDacBS_ListChanged);
            db.ThepDac.Where(t => t.TrangThai).Load();
            thepDacBS.DataSource = db.ThepDac.Local.ToBindingList();
            macVatTuBS = new BindingSource();
            db.MacVatTu.Where(m=>m.TrangThai).Load();
            macVatTuBS.DataSource = db.MacVatTu.Local.ToBindingList();
            //binding for navigator
            thepDacBN.BindingSource = thepDacBS;
            //binding for gridview
            dgvThepDac.AutoGenerateColumns =true;
            dgvThepDac.DataSource = thepDacBS;
            CustomerGridView();
            //binding for textbox
            txtMa.DataBindings.Add("Text", thepDacBS, "MaMatHang");
            txtTen.DataBindings.Add("Text", thepDacBS, "TenMatHang");
            txtChieuDaiPhoi.DataBindings.Add("Text", thepDacBS, "ChieuDaiPhoi");
            txtDuongKinhPhoi.DataBindings.Add("Text", thepDacBS, "DuongKinhPhoi");
            txtChieuDaiCay.DataBindings.Add("Text", thepDacBS, "ChieuDaiCay");
            txtSoChiTietPerCay.DataBindings.Add("Text", thepDacBS, "SoChiTietPerCay");
            txtTrongLuongCay.DataBindings.Add("text", thepDacBS, "TrongLuongCayKG");
            txtTrongLuongPhoiPerChiTiet.DataBindings.Add("Text", thepDacBS, "TrongLuongPhoiPerChiTiet");
            txtTiLeNG.DataBindings.Add("Text", thepDacBS, "TyLeNG");
            //binding for combobox
            cbMacThep.DataBindings.Add("SelectedItem", thepDacBS, "MacThep",true);
            cbMacThep.DataSource = macVatTuBS;
        }
        private void CustomerGridView()
        {
            //Ẩn toàn bộ columns
            foreach (DataGridViewColumn item in dgvThepDac.Columns)
            {
                item.Visible = false;
            }
            //Tùy chỉnh lại
            //Mã
            var c = dgvThepDac.Columns["MaMatHang"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 1;

            //Tên
            c = dgvThepDac.Columns["TenMatHang"];
            c.Visible = true;
            c.Width = 200;
            c.DisplayIndex = 2;

            //mác thép
            c = dgvThepDac.Columns["MacThep"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 3;
            c.ReadOnly = true;

            //Đường kính phôi
            c = dgvThepDac.Columns["DuongKinhPhoi"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 4;
            
            //Chiều dài phôi
            c = dgvThepDac.Columns["ChieuDaiPhoi"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 5;

            //Chiều dài cây
            c = dgvThepDac.Columns["ChieuDaiCay"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 6;

            //Số chi tiết / cây
            c = dgvThepDac.Columns["SoChiTietPerCay"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 7;

            //Trọng lượng cây
            c = dgvThepDac.Columns["TrongLuongCayKG"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 8;

            //Trọng lượng phôi / chi tiết
            c = dgvThepDac.Columns["TrongLuongPhoiPerChiTiet"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 9;

            //Tỷ lệ NG
            c = dgvThepDac.Columns["TyLeNG"];
            c.Visible = true;
            c.Width = 100;
            c.DisplayIndex = 10;
        }
        private void SaveChange()
        {
            if (HasChanged)
            {
                if (MessageBox.Show("Lưu thay đổi ?", "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    db.SaveChanges();
                }
            }          
        }

        /// <summary>
        /// Kiểm tra có trùng mã ko
        /// Dung cho truong hop them moi
        /// True : Ko trùng
        /// False :Trùng
        /// </summary>
        /// <param name="maMatHang"></param>
        /// <returns></returns>
        private bool KiemTraTrungMa(string maMatHang)
        {
            List<MatHang> listMatHang = db.MatHang.Where(m=>m.TrangThai).ToList();
            if (listMatHang.Any(l =>l.MaMatHang.Equals(maMatHang)))
                return false;
            return true;
        }
        /// <summary>
        /// Kiem tra co trung ma ko
        /// Dung cho truong hop edit
        /// 
        /// </summary>
        /// <param name="maMatHang"></param>
        /// <param name="thepDac"></param>
        /// <returns></returns>
        private bool KiemTraTrungMa(string maMatHang, ThepDac thepDac)
        {
            List<MatHang> listMatHang = db.MatHang.Where(m => m.TrangThai).ToList();
            if (listMatHang.Any(l => !l.Equals(thepDac) && l.MaMatHang.Equals(maMatHang)))
                return false;
            return true;
        }
        private void ExportToExcel()
        {
            string workbookPath=@"c:\JAT_VatTu_DanhMucThepDac";
            Excel.Application xlApp=new Excel.Application();
            Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(workbookPath,
                0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);
            Excel.Worksheet xlWorkSheet=(Excel.Worksheet)xlWorkBook.Worksheets[1];
            xlWorkBook.Activate();
            xlWorkSheet.Name="ThepDac";
            //Add data
            var listThepDac=thepDacBS.List;
            int count=0;
            Excel.Range r;
            foreach(ThepDac item in listThepDac)
            {
                xlWorkSheet.Cells[8+count, 1]=count+1;
                xlWorkSheet.Cells[8 + count, 2] = item.MaMatHang;
                xlWorkSheet.Cells[8 + count, 3] = item.TenMatHang;
                xlWorkSheet.Cells[8 + count, 4] = item.MacThep.Tenmac;
                xlWorkSheet.Cells[8 + count, 5] = item.DuongKinhPhoi;
                xlWorkSheet.Cells[8 + count, 6] = item.ChieuDaiPhoi;
                xlWorkSheet.Cells[8 + count, 7] = item.SoChiTietPerCay;
                xlWorkSheet.Cells[8 + count, 8] = item.ChieuDaiCay;
                xlWorkSheet.Cells[8 + count, 9] = item.TrongLuongCayKG;
                xlWorkSheet.Cells[8 + count, 10] = item.TrongLuongPhoiPerChiTiet;
                xlWorkSheet.Cells[8 + count, 11] = item.TyLeNG;

                //Format it               

                string start = "A" + (count + 8).ToString();
                string stop = "K" + (count + 8 ).ToString();
                r = (Excel.Range)xlWorkSheet.get_Range(start,stop);
                r.Borders.Color = Color.Black;
                r.RowHeight = 30;
                //r.Style.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
                r.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, Excel.XlColorIndex.xlColorIndexAutomatic);
                count++;
                
            }
            // Ẩn chương trình
            xlApp.Visible = false;

            // Save file
            xlWorkBook.SaveAs("C:\\JAT_VatTu_DanhMucThepDac_1.xls", Excel.XlFileFormat.xlWorkbookNormal,
                            null, null, false, false,
                            Excel.XlSaveAsAccessMode.xlExclusive,
                            false, false, false, false, false);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);


            
            MessageBox.Show("File created !");
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        } 
        #endregion
        #region Events
        private void frmThepDacDetail_Load(object sender, EventArgs e)
        {
           
            BindData();
            HasChanged = false;
        }
        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            SaveChange();
        }
        private void dgvThepDac_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            Common.ShowMessengerError(e.Exception.Message);
        }

        private void dgvThepDac_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {

            // Bắt lỗi cho cell MaMatHang

            if (dgvThepDac.Columns[e.ColumnIndex].Name == "MaMatHang")
            {
                if (this.dgvThepDac.IsCurrentCellInEditMode)
                {
                    Guid oldId = (Guid)dgvThepDac.CurrentRow.Cells["Id"].Value;
                    if (oldId == null) return;
                    ThepDac oldThepDac = db.ThepDac.FirstOrDefault(t => t.Id.Equals(oldId));
                    if (oldThepDac == null) return;
                    if (!KiemTraTrungMa(e.FormattedValue.ToString(), oldThepDac))
                    {
                        Common.ShowMessengerError("Mã này đã được sử dụng");
                        this.dgvThepDac.EditingControl.Text = oldThepDac.MaMatHang;
                        e.Cancel = true;
                    }
                }
            }

        }

        private void dgvThepDac_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            var value = dgvThepDac.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

            //Bắt lỗi cho cell TyLeNG
            if (dgvThepDac.Columns[e.ColumnIndex].DataPropertyName == "TyLeNG")
            {
                double tryDouble;
                if (Double.TryParse(value.ToString(), out tryDouble))
                {
                    if (tryDouble < 0 || tryDouble > 100)
                    {
                        Common.ShowMessengerError("TyLeNG is not valid! " + tryDouble.ToString());
                        dgvThepDac.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                    }
                }
                else
                {
                    Common.ShowMessengerError("TyLeNG is not valid!");
                    dgvThepDac.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
                }
            }

        }


        private void thepDacBS_AddingNew(object sender, AddingNewEventArgs e)
        {

            ThepDac thepDac = new ThepDac();
            LoaiVatTu loaiVatTu = db.LoaiVatTu.FirstOrDefault(l => l.TenLoai.Equals("Thép Đặc"));
            if (loaiVatTu == null)
            {
                loaiVatTu = new LoaiVatTu();
                loaiVatTu.TenLoai = "Thép Đặc";

            }
            MacVatTu macVatTu = db.MacVatTu.FirstOrDefault(m => m.LoaiVatTu.TenLoai.Equals("Thép Đặc"));
            if (macVatTu == null)
            {
                macVatTu = new MacVatTu();
                macVatTu.LoaiVatTu = loaiVatTu;
                macVatTu.Tenmac = "SH100";
            }
            thepDac.LoaiVatTu = loaiVatTu;
            thepDac.MacThep = macVatTu;
            e.NewObject = thepDac;

        }
        private void thepDacBS_ListChanged(object sender, ListChangedEventArgs e)
        {
            HasChanged = true;
        }
        private void printToolStripButton_Click(object sender, EventArgs e)
        {

        }

        private void exportToolTripButton_Click(object sender, EventArgs e)
        {
            ExportToExcel();
        }
        #endregion

        private void frmThepDacDetail_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveChange();
        }

}
}
